<template>
    <div>
        <van-nav-bar class="title" title="账户登录"/>
        <div class="avatar_info" >
        <van-image
          class="avatar"
          src="https://img01.yzcdn.cn/vant/cat.jpeg"
          fit="cover"
          round
        />
        </div>
        <van-form ref="loginForm">
            <van-field
                v-model="user.mobile"
                name="mobile"
                label="手机号码"
                placeholder="请输入手机账号/手机号码"
                :rules="userFormRules.mobile"
            />
            <van-field
                v-model="user.password"
                type="password"
                name="password"
                label="密码"
                placeholder="请输入密码"
                :rules="userFormRules.password"
            />
            <div style="margin: 16px;">
                <van-button round block type="info" native-type="submit" @click="onSubmit">登录</van-button>
            </div>
            <div class="reg">
                <div class="span">没有账号？立即<a href="#" @click="toRegister">注册</a></div>
            </div>
        </van-form>
    </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      user: {
        mobile: '', // 手机号
        password: '' // 密码
      },
      userFormRules: {
        mobile: [
          { required: true, message: '手机号不能为空！' },
          { pattern: /^1[3|5|7|8]\d{9}$/, message: '手机号格式错误！' }],
        password: [
          { required: true, message: '密码不能为空！' },
          { pattern: /^\d{6,12}$/, message: '密码长度要在6~12位！' }]
      }
    }
  },
  methods: {
    async onSubmit () {
      // this.$toast.loading({
      //   message: '登陆中...',
      //   forbidClick: true, // 禁用背景点击
      //   duration: 0 // 展示Toast的时间，默认为2s，单位为毫秒
      // })
      try {
        await this.$refs.loginForm.validate()
        await this.$store.dispatch('user/login', this.user)
        this.$toast.success('登录成功！')
        this.$router.push({ name: 'Home' })
      } catch (err) {
        if (err.status === 400) { this.$toast.fail(err.message) }
      }
    },
    toRegister () {
      this.$router.push('/register')
    }
  }
}

</script>

<style scoped lang="less">
    /deep/.title {
        background-color: #20a0ff;
        text-align: center;
    }
    .span{
      text-align: center;
      font-size: 16px;
    }
</style>
